<script>
  import { describe } from '$lib';
  import { getActions } from '$lib/actions';
  import { Description } from '$lib/components';
  import { log } from '$lib/log';
  import { getPlayer } from '$lib/player';
  import { entityToObject } from '$lib/serialize';
  import { simulateWorld } from '$lib/simulate';
  import { update } from '$lib/ui';
  import { decode } from '$lib/util';

  let { world, selected, zoomlevel, debug } = $props();
  let trigger = $state(false);
  let actions = $derived((trigger, getActions(world, selected)));
  let pc = $derived(getPlayer(world));
  let extraStyle = $derived(zoomlevel ? `font-size: ${zoomlevel*0.6}px` : '');

  const clicked = ({name, actionCheck}) => {
    const { error, action } = actionCheck(selected)(world, pc);
    console.log(error, action);
    if (!error) {
      simulateWorld(world, actionCheck(selected));
      update();
      trigger = !trigger;
    } else {
      log(`You can't ${name} because ${error}`);
      update();
    }
  };

  const isActiveClass = ({actionCheck}) => {
    const { error } = actionCheck(selected)(world, pc);
    if (error)
      return 'inactive';
    return '';
  };
</script>

<section class="info" style={extraStyle}>
  {#if selected !== undefined}
    <h3 style={extraStyle}>-- {describe(world, selected)} --</h3>
    <p style={extraStyle}>{decode(Description.description[selected ?? 0])}</p>
    {#if debug}
      <div>
        {JSON.stringify(entityToObject(world, selected))}
      </div>
    {/if}
    {#each actions as action}
      <button class="{isActiveClass(action)}" onclick={() => clicked(action)}>
        {action.name}
      </button>
    {/each}
  {/if}
</section>

<style>
  button {
    display: block;
  }

  .inactive {
    color: #766;
  }
</style>
